//
//  WZTabbarTool.swift
//  WZApp
//
//  Created by evol on 2018/6/12.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import HandyJSON


let tabbarHeight:CGFloat = 60.0

class ELTabbarTool: UIView {
    
    let iphoneXBottomMargin:CGFloat = 23.0
    var viewModel: ELTabbarViewModel!
    var datas = [ELTabbarMainModel]()
    var subs = [ELTabbarSubModel]()
    var currentIndex = -1
    var currentSubIndex = -1
    
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0.0
        layout.minimumInteritemSpacing = 0.0
        layout.scrollDirection = .horizontal
        layout.estimatedItemSize = CGSize(width: SCREEN_WIDTH/5, height: tabbarHeight)
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ELTabbarMainCell.self, forCellWithReuseIdentifier: "Main")
        collectionView.register(ELTabbarSubCell.self, forCellWithReuseIdentifier: "Sub")
        return collectionView
    }()
    
    init(_ viewModel:ELTabbarViewModel) {
        super.init(frame:.zero)
        self.viewModel = viewModel
        parseJsonFile() // 解析配置文件
        
        // 定位按钮
        let locationButton = UIButton(type: UIButtonType.custom)
        locationButton.setImage(UIImage(named: "tabbar_location"), for: .normal)
        self.addSubview(locationButton)
        locationButton.snp.makeConstraints {
            $0.top.equalTo( self )
            $0.left.equalTo( 15.0 )
        }
        
        let contentView = UIView()
        contentView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        self.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.top.equalTo(locationButton.snp.bottom).offset(5.0)
            make.height.equalTo(UIDevice.current.isPhoneX ? iphoneXBottomMargin + tabbarHeight : iphoneXBottomMargin)
        }

        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(contentView)
            make.height.equalTo(tabbarHeight)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func parseJsonFile() {
        if let data = WZUtil.readJson("tabbar_config") as? Array<Any> {
            datas += data.compactMap({ELTabbarMainModel.deserialize(from: $0 as? Dictionary)})
        }
    }
}



extension ELTabbarTool: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count + subs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if inSub(indexPath.row) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Sub", for: indexPath) as! ELTabbarSubCell
            cell.model = subs[realIndex(indexPath.row, sub: true)]
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Main", for: indexPath) as! ELTabbarMainCell
            let real_index = realIndex(indexPath.row, sub: false)
            cell.model = datas[real_index]
            cell.separateView.isHidden =
                real_index == datas.count - 1 && !datas[real_index].selected
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if inSub(indexPath.row) {
            let real_index = realIndex(indexPath.row, sub: true)
            if currentSubIndex != real_index {
                cancelSub()
                let subModel = subs[real_index]
                let cell = collectionView.cellForItem(at: indexPath) as! ELTabbarSubCell
                subModel.selected = true
                cell.pitchOn = true
                viewModel.selectSubCommand.onNext(subModel.id)
                currentSubIndex = real_index
            }

        }else{
            if currentIndex >= 0 { //如果上次有选中 先取消选中 如果这次点击跟上次一样那就是取消选中 并结束
                let lastCell = collectionView.cellForItem(at: IndexPath(row: currentIndex, section: 0)) as! ELTabbarMainCell
                let lastModel = datas[currentIndex]
                lastModel.selected = false
                lastCell.picthOn = false
                if currentIndex == realIndex(indexPath.row, sub: false) {
                    if subs.count > 0 {             //如果现在正在展开 先收起来
                        cancelSub()
                        let indexPathSetDel = (0..<subs.count).compactMap({ IndexPath(item: currentIndex + 1 + $0, section: 0)})
                        collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            self.subs.removeAll()
                            collectionView.deleteItems(at: indexPathSetDel)
                            self.currentIndex = -1
                        }
                    }else{
                        self.currentIndex = -1
                    }
                    //
                    viewModel.cancelCommand.onNext(self.currentIndex)
                    return
                }
            }
            
            let cell = collectionView.cellForItem(at: indexPath) as! ELTabbarMainCell
            let model = datas[realIndex(indexPath.row, sub: false)]
            
            if model.sub.count > 0 { //         如果需要展开 默认选中第一个
                let subModel = model.sub.first
                subModel?.selected = true
                currentIndex = realIndex(indexPath.row, sub: false)
                if subs.count > 0 {
                    cancelSub()
                    subs.removeAll()
                }
                currentSubIndex = 0
                subs += model.sub
                model.selected = true
                collectionView.reloadData()
                collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: true)
                viewModel.selectSubCommand.onNext((subModel?.id)!)
            }else{
                if subs.count > 0 {             //如果现在正在展开 先收起来
                    cancelSub()
                    let indexPathSetDel = (0..<subs.count).compactMap({ IndexPath(item: currentIndex + 1 + $0, section: 0)})
                    collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: UICollectionViewScrollPosition.left, animated: true)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        self.subs.removeAll()
                        collectionView.deleteItems(at: indexPathSetDel)
                    }
                }
                model.selected = true
                cell.picthOn = true
                currentIndex = realIndex(indexPath.row, sub: false)
                viewModel.selectCommand.onNext(model.id)
            }
        }
    }
    
    func inSub(_ index:NSInteger) -> Bool {
        return currentIndex < index && index <= currentIndex + subs.count
    }
    
    func realIndex(_ index:NSInteger, sub:Bool) -> NSInteger {
        if sub {
            return index - currentIndex - 1
        }else{
            if index <=  currentIndex {
                return index
            }else{
                return index - subs.count
            }
        }
    }
    
    func cancelSub() -> Void {
        let lastSubModel = subs[currentSubIndex]
        let lastCell = collectionView.cellForItem(at: IndexPath(row: currentIndex + currentSubIndex + 1, section: 0)) as? ELTabbarSubCell
        lastSubModel.selected = false
        if lastCell != nil {
            lastCell?.pitchOn = false
        }
    }
    
}
